// 这不是解构赋值。而是react里用了分别暴露
import React, {Component} from 'react'
import './index.css'

// 创建并暴露组件
export default class Index extends Component{
  state = {list: []}
  listRef = React.createRef()

  // 组件加载完毕
  componentDidMount() {
    this.timer = setInterval(() => {
      const {list} = this.state
      const item = `新闻${list.length + 1}`
      this.setState({list: [item, ...list]})
    }, 1000)
  }

  // 更新前获取快照
  getSnapshotBeforeUpdate() {
    // 返回list的内容区高度
    return this.listRef.current.scrollHeight
  }

  // 更新完
  componentDidUpdate(prevProps, prevState, height) {
    this.listRef.current.scrollTop += this.listRef.current.scrollHeight - height
  }

  // 组件将要销毁时的钩子
  componentWillUnmount() {
    clearInterval(this.timer)
  }

  render() {
    const {list} = this.state
    return(
      <div className="list" ref={this.listRef}>
        {
          list.map((v,i) => {
            return (<div className="item" key={i}>{v}</div>)
          })
        }
      </div>
    )
  }
}
